package com.huawei.esdk.tp.domain.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.huawei.esdk.platform.common.SDKResult;
import com.huawei.esdk.platform.common.bean.config.DeviceConfig;
import com.huawei.esdk.platform.common.config.ConfigManager;
import com.huawei.esdk.platform.common.exception.SDKException;
import com.huawei.esdk.platform.common.utils.StringUtils;
import com.huawei.esdk.platform.nemgr.itf.IDeviceManager;
import com.huawei.esdk.tp.domain.model.bean.PagedList;
import com.huawei.esdk.tp.domain.model.bean.QueryCondition;
import com.huawei.esdk.tp.domain.model.bean.QuerySites;

public class SiteInfoCommService
{
    private static final Logger LOGGER = Logger.getLogger(SiteInfoCommService.class);
    
    private List<Site> siteList;
    
    private Date lastRefreshTime;
    
    private IDeviceManager deviceManager;
    
    /**
     * 通过输入多个会场的uri，返回多个会场的信息 如果某个会场uri不存在或者为空，返回null
     * 
     * @param uri
     * @return
     * @throws SDKException 
     */
    public List<Site> getSiteInfoList(List<String> siteUris)
        throws SDKException
    {
        if (null == siteUris || 0 == siteUris.size())
        {
            return null;
        }
        
        List<Site> resSiteInfo = new ArrayList<Site>();
        
        boolean flag = true;
        for (String uri : siteUris)
        {
            for (Site site : getSite())
            {
                if (site.getUri().equals(uri))
                {
                    resSiteInfo.add(site);
                    flag = false;
                }
            }
            // 如果某个uri不是有效的会场信息，返回null
            if (flag)
            {
                return null;
            }
            
        }
        return resSiteInfo;
    }
    
    /**
     * 调用网元中提供的接口，判断输入的siteUri是否在网元返回的siteInfo中
     * 
     * @param siteUri
     * @return
     * @throws SDKException 
     */
    public boolean containSite(String siteUri)
        throws SDKException
    {
        if (StringUtils.isEmpty(siteUri))
        {
            return false;
        }
        
        // modify by c00316442 2015.1.15,优化查询逻辑,只查对应会场信息,不需要全量查
        //for (Site site : getSite())
        //{
        //    String uri = site.getUri();
        //    if (siteUri.equals(uri))
        //    {
        //        return true;
        //    }
        //}
        
        if (null != querySiteBySiteUri(siteUri))
        {
            return true;
        }
        
        return false;
    }
    
    /**
     * 查询会场是否在device.xml配置文件中已配置
     */
    public boolean containSiteDevice(String siteUri)
    {
        if (StringUtils.isEmpty(siteUri))
        {
            return false;
        }
        
        List<DeviceConfig> deviceList = deviceManager.queryAllDeviceInfo();
        for (DeviceConfig device : deviceList)
        {
            if (device.getDeviceId().equals(siteUri))
            {
                return true;
            }
        }
        return false;
    }
    
    /** 
    * 根据会场Uri查询会场信息
    * add by c00316442 2015.1.15新增，优化原查询所有会场的场景，提高接口调用性能，废弃使用getSite()
    * @param siteUri 会场uri
    * @return Site会场信息
    * @throws SDKException SDK异常
    * @see [类、类#方法、类#成员]
    */
    public Site querySiteBySiteUri(String siteUri)
        throws SDKException
    {
        QuerySites querySites = new QuerySites();
        
        // 设置查询条件
        querySites.setCurrentPage(1);
        
        // 会场Uri不会重复，因此只需要查一条记录即可
        querySites.setNumberPerPage(1);
        QueryCondition queryCondition = new QueryCondition();
        
        // 根据会场Uri查询会场
        queryCondition.setConditionName("StringFilterEx");
        queryCondition.setConditionType("1");
        queryCondition.setConditionValue(new Object[] {1, siteUri});
        List<QueryCondition> queryConditionList = new ArrayList<QueryCondition>();
        queryConditionList.add(queryCondition);
        querySites.setQueryCondition(queryConditionList);
        
        SDKResult<PagedList<Site>> result = Site.querySites(querySites);
        
        if (0 != result.getErrCode())
        {
            return null;
        }
        else
        {
            List<Site> sites = result.getResult().getRecords();
            
            if (!sites.isEmpty())
            {
                return sites.get(0);
            }
            else
            {
                return null;
            }
        }
    }
    
    /**
     * 调用业务接口，查询所有的会场信息
     * add Deprecated 2015.1.15 by c00316442
     * @return
     * @throws SDKException 
     */
    @Deprecated
    public List<Site> getSite()
        throws SDKException
    {
        if (null != siteList && !needRefresh())
        {
            return siteList;
        }
        
        QuerySites querySites = new QuerySites();
        querySites.setNumberPerPage(Integer.parseInt(ConfigManager.getInstance()
            .getValue("professional.queryAllSites.totalNumber")));
        querySites.setCurrentPage(1);
        SDKResult<PagedList<Site>> result = Site.querySites(querySites);
        if (0 == result.getErrCode())
        {
            List<Site> sites = result.getResult().getRecords();
            //Update the site and refresh time
            siteList = sites;
            lastRefreshTime = new Date();
            return sites;
        }
        else
        {
            SDKException e = new SDKException("");
            e.setSdkErrCode((int)result.getErrCode());
            throw e;
        }
    }
    
    /**
     * 通过输入会场的uri，返回会场的信息
     * 
     * @param uri
     * @return
     * @throws SDKException 
     */
    public Site getSite(String siteUri)
        throws SDKException
    {
        if (StringUtils.isEmpty(siteUri))
        {
            return null;
        }
        
        // modify by c00316442 2015.1.15,优化查询逻辑,只查对应会场信息,不需要全量查
        //for (Site siteInfo : getSite())
        //{
        //    if (siteInfo.getUri().equals(siteUri))
        //    {
        //        return siteInfo;
        //    }
        //}
        
        Site siteInfo = querySiteBySiteUri(siteUri);
        
        if (null != siteInfo)
        {
            return siteInfo;
        }
        
        return null;
    }
    
    public IDeviceManager getDeviceManager()
    {
        return deviceManager;
    }
    
    public void setDeviceManager(IDeviceManager deviceManager)
    {
        this.deviceManager = deviceManager;
    }
    
    private boolean needRefresh()
    {
        Date now = new Date();
        
        if (null != lastRefreshTime
            && (now.getTime() - lastRefreshTime.getTime()) < 1000L * 60 * getRefreshIntervalAsInt())
        {
            return false;
        }
        LOGGER.debug("needRefresh() return true");
        return true;
    }
    
    public int getRefreshIntervalAsInt()
    {
        String refreshInterval =
            ConfigManager.getInstance().getValue("professional.common.sites.refresh.interval", "30");
        return Integer.parseInt(refreshInterval);
    }
}
